import {
  EyeOutlined,
  HeartFilled,
  HeartOutlined,
  LinkOutlined,
  SearchOutlined,
  LoadingOutlined,
  TagOutlined,
  GlobalOutlined,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Card, Input, Tag, Typography, message, Skeleton, Tooltip, Space, Tree } from 'antd';
import React, { useEffect, useState, useMemo } from 'react';
import styles from './index.less';
import type { Category, Link } from '@/services/generated/models';
import { api } from '@/services/api';
import { find, filter, groupBy, flatMap, flatten, map } from 'lodash';

const { Search } = Input;
const { Title, Text } = Typography;

const IndexPage: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [categories, setCategories] = useState<Category[]>([]);
  const [links, setLinks] = useState<Link[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [showFavorites, setShowFavorites] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);

  // 获取所有分类（包括子分类）
  const fetchAllCategories = async () => {
    try {
      const data = await api.navigation.navigationCategoriesList();
      setCategories(data);
    } catch (error) {
      message.error('加载分类失败');
      console.error('Error fetching categories:', error);
    }
  };

  // 获取链接数据
  const fetchLinks = async (params: { search?: string } = {}) => {
    try {
      const data = await api.navigation.navigationLinksList(params);
      setLinks(data);
    } catch (error) {
      message.error('加载链接失败');
      console.error('Error fetching links:', error);
    }
  };

  const fetchData = async () => {
    setLoading(true);
    try {
      await Promise.all([fetchAllCategories(), fetchLinks()]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 处理搜索
  const handleSearch = async (value: string) => {
    setSearchText(value);
    setLoading(true);
    try {
      await fetchLinks({ search: value });
    } finally {
      setLoading(false);
    }
  };

  // 处理收藏切换
  const handleFavoriteClick = async (id: number) => {
    try {
      const currentLink = links.find(l => l.id === id);
      if (currentLink) {
        await api.navigation.navigationLinksPartialUpdate({
          id,
          patchedLinkRequest: { isFavorite: !currentLink.isFavorite }
        });
        message.success(currentLink.isFavorite ? '已取消收藏' : '已添加到收藏');
        fetchLinks();
      }
    } catch (error) {
      message.error('更新收藏状态失败');
      console.error('Favorite toggle error:', error);
    }
  };

  // 处理链接点击
  const handleLinkClick = async (link: Link) => {
    try {
      await api.navigation.navigationLinksPartialUpdate({
        id: link.id,
        patchedLinkRequest: { views: (link.views || 0) + 1 }
      });
      window.open(link.url, '_blank');
    } catch (error) {
      message.error('更新访问次数失败');
      console.error('View count update error:', error);
    }
  };

  // 递归查找分类及其所有子分类ID
  const getAllCategoryIds = (categoryId: number, categories: Category[]): number[] => {
    const category = find(categories, { id: categoryId });
    if (!category) return [categoryId];
    
    return [categoryId, ...flatMap(category.children || [], (child: Category) => child.id)];
  };

  // 过滤链接
  const filteredLinks = useMemo(() => {
    return filter(links, link => {
      // 收藏过滤
      if (showFavorites && !link.isFavorite) return false;
      
      // 分类过滤
      if (selectedCategory) {
        console.log(selectedCategory,'selectedCategory');
        const categoryIds = getAllCategoryIds(selectedCategory, categories);
        const matchingCategories = categories.filter(cat => categoryIds.includes(cat.id));
        return matchingCategories.some(cat => cat.name === link.categoryName);
      }
      
      return true;
    });
  }, [links, showFavorites, selectedCategory, categories]);

  // 按分类分组的链接
  const linksByCategory = useMemo(() => {
    // 先按分类ID分组
    const groupedLinks = groupBy(filteredLinks, 'categoryName');
    console.log(filteredLinks,'filteredLinks');
    console.log(groupedLinks,'groupedLinks');
    // 转换成需要的格式并过滤掉空分类

   
    const flattenedCategories = flatMap(categories, category => [category, ...(category.children || [])]);
    return filter(
      flattenedCategories.map(category => ({
        category,
        links: groupedLinks[category.name] || []
      })),
      group => group.links.length > 0
    );
  }, [categories, filteredLinks]);

  // 转换分类数据为Tree数据
  const categoryTreeData = useMemo(() => {
    const convertToTreeData = (categories: Category[]) => {
      return categories.map(category => ({
        title: category.name,
        key: category.id,
        children: category.children ? convertToTreeData(category.children) : undefined
      }));
    };
    return convertToTreeData(categories);
  }, [categories]);

  // 渲染分类树
  const renderCategoryTree = () => {
    return (
      <div className={styles.categoryTree}>
        <Tree
          treeData={categoryTreeData}
          selectedKeys={selectedCategory ? [selectedCategory.toString()] : []}
          onSelect={(selectedKeys) => {
            const categoryId = selectedKeys.length > 0 ? Number(selectedKeys[0]) : null;
            setSelectedCategory(categoryId);
          }}
        />
      </div>
    );
  };

  const renderLinkCard = (item: Link) => (
    <Card
      key={item.id}
      hoverable
      className={styles.card}
      bodyStyle={{ padding: 0 }}
      onClick={() => handleLinkClick(item)}
    >
      <div className={styles.cardContent}>
        <div className={styles.imageContainer}>
          {item.icon ? (
            <img src={item.icon} alt={item.title} />
          ) : (
            <GlobalOutlined className={styles.defaultIcon} />
          )}
        </div>
        <div className={styles.textContent}>
          <div className={styles.title}>
            <Tooltip title={item.title}>
              <Text ellipsis>{item.title}</Text>
            </Tooltip>
            <LinkOutlined className={styles.linkIcon} />
          </div>
          <div className={styles.description}>
            <Tooltip title={item.description}>
              <Text ellipsis>{item.description}</Text>
            </Tooltip>
          </div>
          <Space className={styles.stats}>
            <Tooltip title="访问次数">
              <span className={styles.statItem}>
                <EyeOutlined />
                <span>{item.views || 0}</span>
              </span>
            </Tooltip>
            {item.tags && item.tags.length > 0 && (
              <Tooltip title="标签">
                <span className={styles.statItem}>
                  <TagOutlined />
                  <span>{item.tags.length}</span>
                </span>
              </Tooltip>
            )}
            <Tooltip title={item.isFavorite ? "取消收藏" : "添加到收藏"}>
              <span
                className={`${styles.statItem} ${styles.favorite}`}
                onClick={(e) => {
                  e.stopPropagation();
                  handleFavoriteClick(item.id);
                }}
              >
                {item.isFavorite ? (
                  <HeartFilled style={{ color: '#ff4d4f' }} />
                ) : (
                  <HeartOutlined />
                )}
              </span>
            </Tooltip>
          </Space>
        </div>
      </div>
    </Card>
  );

  return (
    <div className={styles.container}>
      <div className={styles.searchBar}>
        <Search
          placeholder="搜索链接..."
          allowClear
          enterButton={<SearchOutlined />}
          size="large"
          onSearch={handleSearch}
          loading={loading}
        />
        <div className={styles.filters}>
          <Tag
            className={styles.filterTag}
            color={showFavorites ? 'red' : 'default'}
            icon={<HeartFilled />}
            onClick={() => setShowFavorites(!showFavorites)}
          >
            收藏
          </Tag>
          {renderCategoryTree()}
        </div>
      </div>

      <div className={styles.content}>
        {loading ? (
          <div className={styles.loading}>
            <Skeleton active />
            <Skeleton active />
            <Skeleton active />
          </div>
        ) : linksByCategory.length === 0 ? (
          <div className={styles.empty}>
            <Text type="secondary">没有找到匹配的链接</Text>
          </div>
        ) : (
          linksByCategory.map(({ category, links }) => (
            <div key={category.id} className={styles.categorySection}>
              <Title level={3}>
                {category.name}
                <span className={styles.categoryCount}>
                  ({links.length})
                </span>
              </Title>
              <div className={styles.cardGrid}>
                {links.map(renderLinkCard)}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default IndexPage;
